package com.javaclimb.drug.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName ShiroFilterConfiguration.java
 * @Description TODO 权限控制Shiro配置类
 * @createTime 2021年10月02日 12:18:00
 */
@Configuration
public class ShiroFilterConfiguration {

    /**
     * 创建过滤工厂Bean
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager());
        /**
         * shiro内置过滤器 实现权限相关的拦截器
         * anon 无序登陆可以访问
         * authc：必须登陆才可以访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/static/**","anon");
        filterMap.put("/login","anon");
        filterMap.put("/toLogin","anon");
        filterMap.put("/**","authc");
        factoryBean.setFilterChainDefinitionMap(filterMap);
        // 不登录自动转向的页面
//        shiroFilterFactoryBean().setLoginUrl("/login");
        factoryBean.setLoginUrl("/login");

        // 登录后自动转向的页面
//        shiroFilterFactoryBean().setSuccessUrl("/index");
        factoryBean.setSuccessUrl("/index");
        return factoryBean;
    }

    /**
     *权限管理
     */
    @Bean
    public DefaultWebSecurityManager securityManager(){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(userRealm());
        return manager;
    }

    /**
     * 创建一个Realm 认证用
     * @return
     */
    @Bean
    public UserRealm userRealm(){
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }

    /**
     *
     * thymeleaf 整合shiro
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return  new ShiroDialect();
    }
}
